/*
 * Copyright (C) 2018 The Asiainfo-Ability Authors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package org.asiainfo.ability.manager.controler;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.asiainfo.ability.base.utils.JsonUtils;
import org.asiainfo.ability.base.utils.StringUtils;
import org.asiainfo.ability.gateway.model.Instance;
import org.asiainfo.ability.manager.service.AgentService;
import org.asiainfo.ability.node.utils.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: visen
 * @Date: 2018/1/16
 * @Description:
 */
@RestController
public class AgentControler {
    private static final Logger logger = LogManager.getLogger(AgentControler.class);
    @Autowired
    private AgentService agentService;


    @RequestMapping(value = "/node/instance/health", method = RequestMethod.GET)
    public void checkInstanceHealth(HttpServletRequest request, HttpServletResponse response) throws Exception {

        CloseableHttpClient httpClient = HttpClient.createHttpClient(0, 3000);
        String ip = request.getParameter("ip");
        String instanceId = request.getParameter("id");
        if (StringUtils.isBlank(instanceId)) {
            StringBuilder url = new StringBuilder("http://");
            url.append(ip);
            try {
                url.append("/testActive");
                HttpGet get = new HttpGet(url.toString());
                HttpResponse resp = httpClient.execute(get);
                setRet(response, EntityUtils.toString(resp.getEntity()));
            } catch (Exception e) {
                logger.error(e);
                setRet(response, "0");
            }
        } else {
            Instance instance = agentService.loadtInstance(Long.parseLong(instanceId));
            setRet(response, instance.getState().toString());

        }

    }

    @RequestMapping(value = "/node/health", method = RequestMethod.GET)
    public void checkNodeHealth(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //System.out.println()
        CloseableHttpClient httpClient = HttpClient.createHttpClient(0, 2000);
        String ip = request.getParameter("ip");
        StringBuilder url = new StringBuilder("http://");
        url.append(ip);
        try {
            url.append("/testActive");
            HttpGet get = new HttpGet(url.toString());
            HttpResponse resp = httpClient.execute(get);
            setRet(response, EntityUtils.toString(resp.getEntity()));
        } catch (Exception e) {
            logger.error(e);
            setRet(response, "0");
        }
    }



    @RequestMapping(value = "/node/process", method = RequestMethod.POST)
    public void processNode(@RequestBody AgentService.BatchOperation batchOperation, HttpServletRequest request, HttpServletResponse response) throws Exception {
        CloseableHttpClient httpClient = HttpClient.createHttpClient(0, 3000);
        List result = new ArrayList();
        setRet(response, JsonUtils.toJSON(agentService.processNode(batchOperation)));

    }

    public void doResponse(HttpServletResponse servletRes, CloseableHttpResponse proxyRes) {
        // 处理消息头
        Header[] headers = proxyRes.getAllHeaders();
        if (headers != null) {
            for (Header header : headers) {
                servletRes.addHeader(header.getName(), header.getValue());
            }
        }
    }


    private void setRet(HttpServletResponse response, String code) {
        try {
            response.getWriter().write(code);
        } catch (IOException e) {
            logger.error("", e);
        }
    }

    public static void main(String[] args) throws Exception {

    }


}
